(defvar xbasic-mode-hook nil)
(defvar xbasic-mode-map
  (let ((xbasic-mode-map (make-keymap)))
    (define-key xbasic-mode-map "\C-j" 'newline-and-indent)
    xbasic-mode-map)
  "Keymap for XBASIC major mode")

(add-to-list 'auto-mode-alist '("\\.bas\\'" . xbasic-mode))

(setq xbasic-keywords 
 '(
   ("^[0-9]+" . font-lock-constant-face)
   ("^[0-9]+ \\(SEARCH\\|CHAIN\\|INPUT\\|PRINT\\|LET\\|DIM\\) "  1 font-lock-builtin-face)
   ("[A-Z][0-9]+" . font-lock-variable-name-face)
   ("[0-9]+" . font-lock-constant-face)
  )
)

;; the command to comment/uncomment text
(defun xbasic-comment-dwim (arg)
  "Comment or uncomment current line or region in a smart way.
For detail, see `comment-dwim'."
  (interactive "*P")
  (require 'newcomment)
  (let ((deactivate-mark nil) (comment-start "REM") (comment-end ""))
    (comment-dwim arg)))


(defun xbasic-indent-line ()
  (let ((linestart 0)
	(lineend 0)
	(delta 10))
    (progn
      (forward-line -1)
      (beginning-of-line)
      (if (looking-at "^\\([0-9]+\\)")
	  (set 'linestart (string-to-int (match-string 1)))
      )
      ;; Bug, non funziona se sono alla fine del file
      (forward-line 2)
      (if (looking-at "^\\([0-9]+\\)")
	  (set 'lineend (string-to-int (match-string 1)))
	)
      (if (< (- lineend linestart) 20)
	  (set 'delta 5)
	)
      (if (< (- lineend linestart) 10)
	  (set 'delta 1)
	)
      (if (= lineend 0)
	  (set 'delta 10)
	)
      (forward-line -1)
      (beginning-of-line)
      (insert (format "%d " (+ linestart delta)))
      )
    )
  )

(defun xbasic-mode ()
  (interactive)
  (kill-all-local-variables)
  (use-local-map xbasic-mode-map)
;;  (set-syntax-table xbasic-mode-syntax-table)
  ;; Set up font-lock
  (set (make-local-variable 'font-lock-defaults) '(xbasic-keywords))
  ;; Register our indentation function
  (set (make-local-variable 'indent-line-function) 'xbasic-indent-line)  
  (setq major-mode 'xbasic-mode)
  (setq mode-name "XBASIC")
;;;   (run-hooks 'xbasic-mode-hook))
)

 (provide 'xbasic-mode)

